<template>
  <div v-loading="loading" class="announcement-list-container">
    <!-- 筛选器 -->
    <div class="filter-bar">
      <el-form :model="queryParams" inline>
        <el-form-item label="阅读状态">
          <el-select
            v-model="queryParams.readStatus"
            placeholder="全部"
            clearable
            style="width: 120px"
            @change="handleQuery"
          >
            <el-option label="未读" :value="0" />
            <el-option label="已读" :value="1" />
            <el-option label="已忽略" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select
            v-model="queryParams.type"
            placeholder="全部"
            clearable
            style="width: 120px"
            @change="handleQuery"
          >
            <el-option label="系统公告" :value="1" />
            <el-option label="活动公告" :value="2" />
            <el-option label="维护公告" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告级别">
          <el-select
            v-model="queryParams.level"
            placeholder="全部"
            clearable
            style="width: 120px"
            @change="handleQuery"
          >
            <el-option label="普通" :value="1" />
            <el-option label="重要" :value="2" />
            <el-option label="紧急" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 公告列表 -->
    <div v-if="announcementList.records.length > 0" class="announcements-list">
      <div
        v-for="announcement in announcementList.records"
        :key="announcement.id"
        class="announcement-item"
        :class="{
          'is-unread': announcement.readStatus === null,
          'is-ignored': announcement.ignored
        }"
        @click="handleViewDetail(announcement)"
      >
        <!-- 公告头部 -->
        <div class="item-header">
          <div class="header-left">
            <el-tag
              :type="utils.getLevelInfo(announcement.level).tagType"
              size="small"
              class="level-tag"
            >
              {{ announcement.levelName }}
            </el-tag>
            <el-tag
              :type="utils.getTypeInfo(announcement.type).tagType"
              size="small"
              effect="plain"
            >
              <el-icon>
                <component :is="utils.getTypeInfo(announcement.type).icon" />
              </el-icon>
              {{ announcement.typeName }}
            </el-tag>
            <el-tag v-if="announcement.isTop" type="danger" size="small">
              置顶
            </el-tag>
            <el-tag
              :type="utils.getReadStatusInfo(announcement.readStatus).tagType"
              size="small"
            >
              {{ utils.getReadStatusInfo(announcement.readStatus).label }}
            </el-tag>
          </div>
          <div class="header-right">
            <span class="announcement-time">
              {{ utils.formatTime(announcement.publishTime) }}
            </span>
          </div>
        </div>

        <!-- 公告标题 -->
        <div class="item-title">
          {{ announcement.title }}
        </div>

        <!-- 公告内容预览 -->
        <div class="item-content">
          {{ utils.truncateContent(announcement.content, 150) }}
        </div>

        <!-- 公告元信息 -->
        <div class="item-meta">
          <span class="meta-item">
            <el-icon><View /></el-icon>
            {{ utils.formatNumber(announcement.viewCount) }} 次浏览
          </span>
          <span v-if="announcement.readTime" class="meta-item">
            <el-icon><Clock /></el-icon>
            阅读于 {{ utils.formatTime(announcement.readTime) }}
          </span>
        </div>

        <!-- 操作按钮 -->
        <div class="item-actions" @click.stop>
          <el-button
            v-if="announcement.readStatus === null"
            size="small"
            type="primary"
            plain
            @click="handleMarkAsRead(announcement)"
          >
            <el-icon><Check /></el-icon>
            标记已读
          </el-button>
          <el-button
            v-if="announcement.ignored"
            size="small"
            type="info"
            plain
            @click="handleUnignore(announcement)"
          >
            <el-icon><RefreshLeft /></el-icon>
            取消忽略
          </el-button>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-else description="暂无公告" />

    <!-- 分页 -->
    <div v-if="announcementList.total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :total="announcementList.total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @current-change="handleQuery"
        @size-change="handleQuery"
      />
    </div>

    <!-- 公告详情对话框 -->
    <AnnouncementDetailDialog
      v-model:visible="detailDialogVisible"
      :announcement-id="selectedAnnouncementId"
      @read="handleAnnouncementRead"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Refresh,
  View,
  Clock,
  Check,
  RefreshLeft
} from "@element-plus/icons-vue";
import {
  getMessageCenterAnnouncementsApi,
  markAnnouncementAsReadApi,
  unignoreAnnouncementApi,
  UserAnnouncementUtils,
  type MessageCenterAnnouncementInfo,
  type PageResponse,
  type GetMessageCenterAnnouncementsParams
} from "@/api/user-announcement";
import AnnouncementDetailDialog from "@/views/user/announcement/components/AnnouncementDetailDialog.vue";

// 工具类
const utils = UserAnnouncementUtils;

// 状态
const loading = ref(false);
const detailDialogVisible = ref(false);
const selectedAnnouncementId = ref<number>();

// 定义emit
const emit = defineEmits(["update-count"]);

// 查询参数
const queryParams = ref<GetMessageCenterAnnouncementsParams>({
  current: 1,
  size: 10,
  type: undefined,
  level: undefined,
  readStatus: undefined
});

// 公告列表
const announcementList = ref<PageResponse<MessageCenterAnnouncementInfo>>({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 0
});

// 加载公告列表
const loadAnnouncementList = async () => {
  loading.value = true;
  try {
    const response = await getMessageCenterAnnouncementsApi(queryParams.value);
    if (response.code === 200 && response.data) {
      announcementList.value = response.data;
    } else {
      ElMessage.error(response.message || "加载公告列表失败");
    }
  } catch (error: any) {
    console.error("加载公告列表失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  } finally {
    loading.value = false;
  }
};

// 通知父组件刷新统计
const notifyParentRefresh = () => {
  emit("update-count");
};

// 查询
const handleQuery = () => {
  queryParams.value.current = 1;
  loadAnnouncementList();
};

// 重置
const handleReset = () => {
  queryParams.value = {
    current: 1,
    size: 10,
    type: undefined,
    level: undefined,
    readStatus: undefined
  };
  loadAnnouncementList();
};

// 查看详情
const handleViewDetail = (announcement: MessageCenterAnnouncementInfo) => {
  selectedAnnouncementId.value = announcement.id;
  detailDialogVisible.value = true;
};

// 标记已读
const handleMarkAsRead = async (
  announcement: MessageCenterAnnouncementInfo
) => {
  try {
    const response = await markAnnouncementAsReadApi(announcement.id);
    if (response.code === 200) {
      ElMessage.success("已标记为已读");
      announcement.read = true;
      announcement.readStatus = 1;
      announcement.readStatusName = "已读";
      notifyParentRefresh();
    } else {
      ElMessage.error(response.message || "标记已读失败");
    }
  } catch (error: any) {
    console.error("标记已读失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  }
};

// 取消忽略
const handleUnignore = async (announcement: MessageCenterAnnouncementInfo) => {
  try {
    const response = await unignoreAnnouncementApi(announcement.id);
    if (response.code === 200) {
      ElMessage.success("已取消忽略");
      announcement.ignored = false;
      announcement.readStatus = null;
      announcement.readStatusName = "未读";
      notifyParentRefresh();
    } else {
      ElMessage.error(response.message || "取消忽略失败");
    }
  } catch (error: any) {
    console.error("取消忽略失败:", error);
    ElMessage.error(utils.formatErrorMessage(error));
  }
};

// 公告已读回调
const handleAnnouncementRead = (id: number) => {
  const announcement = announcementList.value.records.find(
    item => item.id === id
  );
  if (announcement) {
    announcement.read = true;
    announcement.readStatus = 1;
    announcement.readStatusName = "已读";
  }
  notifyParentRefresh();
};

// 刷新数据（暴露给父组件调用）
const refresh = () => {
  loadAnnouncementList();
};

// 组件挂载
onMounted(() => {
  loadAnnouncementList();
  notifyParentRefresh();
});

// 暴露方法给父组件
defineExpose({
  refresh
});
</script>

<style scoped lang="scss">
/* 响应式设计 */
@media (width <= 768px) {
  .announcement-list-container {
    .filter-bar {
      padding: 12px;

      .el-form {
        .el-form-item {
          width: 100%;
          margin-right: 0;
          margin-bottom: 12px;

          :deep(.el-form-item__content) {
            width: 100%;

            .el-select {
              width: 100% !important;
            }
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }

    .announcements-list {
      .announcement-item {
        padding: 16px;

        .item-header {
          flex-direction: column;
          gap: 8px;
          align-items: flex-start;

          .header-right {
            width: 100%;

            .announcement-time {
              font-size: 12px;
            }
          }
        }

        .item-title {
          font-size: 16px;
        }

        .item-content {
          font-size: 13px;
        }

        .item-meta {
          gap: 12px;
          font-size: 12px;
        }

        .item-actions {
          .el-button {
            flex: 1;
          }
        }
      }
    }
  }
}

.announcement-list-container {
  .filter-bar {
    padding: 20px;
    margin-bottom: 24px;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-radius: 16px;
    box-shadow: 0 2px 12px rgb(0 0 0 / 4%);

    .el-form {
      margin: 0;

      .el-form-item {
        margin-right: 16px;
        margin-bottom: 0;

        &:last-child {
          margin-right: 0;
        }

        :deep(.el-form-item__label) {
          font-weight: 600;
          color: #334155;
        }

        :deep(.el-select) {
          .el-input__wrapper {
            border-radius: 10px;
            transition: all 0.3s ease;

            &:hover {
              border-color: #667eea;
              box-shadow: 0 0 0 1px rgb(102 126 234 / 20%);
            }

            &.is-focus {
              border-color: #667eea;
              box-shadow: 0 0 0 1px rgb(102 126 234 / 40%);
            }
          }
        }
      }

      .el-button {
        border-radius: 10px;
        transition: all 0.3s ease;

        &:hover {
          color: #667eea;
          background: #eef2ff;
          border-color: #667eea;
        }
      }
    }
  }

  .announcements-list {
    .announcement-item {
      position: relative;
      padding: 24px;
      margin-bottom: 20px;
      overflow: hidden;
      cursor: pointer;
      background: #fff;
      border: 2px solid transparent;
      border-radius: 16px;
      box-shadow: 0 2px 12px rgb(0 0 0 / 4%);
      transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);

      &::before {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
        width: 100%;
        height: 100%;
        content: "";
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        opacity: 0;
        transition: opacity 0.4s ease;
      }

      &:hover {
        border-color: #667eea;
        box-shadow: 0 12px 32px rgb(102 126 234 / 15%);
        transform: translateY(-4px);

        &::before {
          opacity: 0.02;
        }
      }

      &.is-unread {
        background: linear-gradient(135deg, #f0f9ff 0%, #fff 100%);
        border-color: #bae6fd;

        &::after {
          position: absolute;
          top: 12px;
          left: 0;
          z-index: 1;
          width: 4px;
          height: calc(100% - 24px);
          content: "";
          background: linear-gradient(180deg, #3b82f6 0%, #2563eb 100%);
          border-radius: 0 4px 4px 0;
        }

        &:hover {
          border-color: #3b82f6;
        }
      }

      &.is-ignored {
        opacity: 0.6;

        &:hover {
          opacity: 0.8;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }

      .item-header {
        position: relative;
        z-index: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 16px;

        .header-left {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          align-items: center;

          .el-tag {
            display: inline-flex !important;
            gap: 5px;
            align-items: center !important;
            justify-content: center;
            height: 26px;
            padding: 0 12px !important;
            font-size: 13px !important;
            font-weight: 600 !important;
            line-height: 1 !important;
            border-radius: 8px !important;

            :deep(span) {
              display: flex;
              align-items: center;
              font-size: 13px !important;
              font-weight: 600 !important;
              line-height: 1 !important;
            }

            .el-icon {
              display: flex;
              align-items: center;
              margin: 0;
              font-size: 14px !important;
            }
          }
        }

        .header-right {
          .announcement-time {
            font-size: 13px;
            font-weight: 500;
            color: #94a3b8;
            white-space: nowrap;
          }
        }
      }

      .item-title {
        position: relative;
        z-index: 1;
        margin-bottom: 12px;
        font-size: 19px;
        font-weight: 700;
        line-height: 1.5;
        color: #1e293b;
      }

      .item-content {
        position: relative;
        z-index: 1;
        margin-bottom: 16px;
        font-size: 14px;
        line-height: 1.7;
        color: #64748b;
      }

      .item-meta {
        position: relative;
        z-index: 1;
        display: flex;
        flex-wrap: wrap;
        gap: 20px;
        margin-bottom: 16px;
        font-size: 13px;
        color: #94a3b8;

        .meta-item {
          display: flex;
          gap: 6px;
          align-items: center;
          font-weight: 500;

          .el-icon {
            font-size: 15px;
            color: #667eea;
          }
        }
      }

      .item-actions {
        position: relative;
        z-index: 1;
        display: flex;
        gap: 10px;

        .el-button {
          border-radius: 10px;
          transition: all 0.3s ease;

          &.el-button--primary {
            color: #fff;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;

            &:hover {
              box-shadow: 0 4px 12px rgb(102 126 234 / 40%);
              transform: translateY(-2px);
            }
          }

          &.el-button--info {
            color: #64748b;
            background: #f8fafc;
            border: 1px solid #e2e8f0;

            &:hover {
              color: #667eea;
              background: #eef2ff;
              border-color: #667eea;
            }
          }
        }
      }
    }
  }

  .pagination-wrapper {
    display: flex;
    justify-content: center;
    margin-top: 32px;

    :deep(.el-pagination) {
      .el-pager li {
        font-weight: 600;
        border-radius: 8px;
        transition: all 0.3s ease;

        &.is-active {
          color: #fff;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          box-shadow: 0 2px 8px rgb(102 126 234 / 40%);
        }

        &:hover:not(.is-active) {
          color: #667eea;
          background: #eef2ff;
        }
      }

      .btn-prev,
      .btn-next {
        font-weight: 600;
        border-radius: 8px;

        &:hover:not(:disabled) {
          color: #667eea;
          background: #eef2ff;
        }
      }
    }
  }
}
</style>
